/*
 * XDVShader.cpp
 *
 *  Created on: May 21, 2013
 *      Author: daviD
 */

#include "XDVShader.h"
#include <cstdlib>
#include <fstream>
#include <iostream>

using namespace std;

const string Path = string("C:\\Users\\daviD\\Documents\\XDVEngine\\XDVEngine\\src\\Rendering\\");

XDVShader::XDVShader()
{
	m_program = 0;
	m_vertexShader = 0;
	m_fragShader = 0;
}

XDVShader::XDVShader(char* vertexShaderFile, char* fragmentShaderFile)
{
	SetShaders(vertexShaderFile, fragmentShaderFile);
}

XDVShader::~XDVShader()
{
	// TODO Auto-generated destructor stub
}

// Function to initialize shaders.
void XDVShader::SetShaders(char* vertexShaderFile, char* fragmentShaderFile)
{
   char* vertexShader = ReadShader(vertexShaderFile);
   char* fragmentShader = ReadShader(fragmentShaderFile);

   m_program = glCreateProgram();
   m_vertexShader = glCreateShader(GL_VERTEX_SHADER);
   m_fragShader = glCreateShader(GL_FRAGMENT_SHADER);

   glShaderSource(m_vertexShader, 1, (const char**) &vertexShader, NULL);
   glShaderSource(m_fragShader, 1, (const char**) &fragmentShader, NULL);


   glCompileShader(m_vertexShader);
   glCompileShader(m_fragShader);

   glAttachShader(m_program, m_vertexShader);
   glAttachShader(m_program, m_fragShader);

   glLinkProgram(m_program);
   glUseProgram(m_program);

   GLint x;
   glGetShaderiv (m_vertexShader, GL_COMPILE_STATUS,&x);
   if(x == GL_FALSE)
   {
	   char log[500];
	   GLsizei size;
		glGetInfoLogARB(m_vertexShader,  500,  &size, log);
		cerr << log << endl;
   }

   glGetShaderiv (m_fragShader, GL_COMPILE_STATUS,&x);
   if(x == GL_FALSE)
   {
	   char log[500];
	  	   GLsizei size;
	  		glGetInfoLogARB(m_fragShader,  500,  &size, log);
	  		cerr << log << endl;
   }
}


char* XDVShader::ReadShader(char* aShaderFile)
{
	string fileaname = string(aShaderFile);
	string nameToUse = Path + fileaname;
   FILE* filePointer = fopen(nameToUse.c_str(), "rb");
   char* content = NULL;
   long numVal = 0;

   if(filePointer == NULL)
   {
	   cerr << "Error file not found" << endl;
	   cerr << aShaderFile << endl;
   }


   fseek(filePointer, 0L, SEEK_END);
   numVal = ftell(filePointer);
   fseek(filePointer, 0L, SEEK_SET);
   content = (char*) malloc((numVal+1) * sizeof(char));
   fread(content, 1, numVal, filePointer);
   content[numVal] = '\0';
   fclose(filePointer);
   return content;
}

